package com.lzwk.app.function;

import com.alibaba.fastjson.JSONObject;
import org.datanucleus.store.types.wrappers.backed.Map;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

/**
 * @Author: CC
 * @Date: 2022/3/7 20:02
 */
public class StatLogParse {

    private static String TruncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;

        strURL = strURL.trim().toLowerCase();

        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                if (arrSplit[1] != null) {
                    strAllParam = arrSplit[1];
                }
            }
        }
        return strAllParam;
    }

    public static JSONObject URLRequest(String URL) {
        JSONObject jsonRequest = new JSONObject();

        String[] arrSplit;

        String strUrlParam = TruncateUrlPage(URL);
        if (strUrlParam == null) {
            return jsonRequest;
        }

        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            if (arrSplitEqual.length > 1) {
                jsonRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            } else {
                if (arrSplitEqual[0] != "") {
                    jsonRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return jsonRequest;

    }

    public static JSONObject run(JSONObject jsonObjectStatLog) {
        JSONObject jsonObjectResult = new JSONObject();
        String request = jsonObjectStatLog.getString("request");
        jsonObjectResult.put("referer", jsonObjectStatLog.getOrDefault("http_referer", ""));
        jsonObjectResult.put("remote_address", jsonObjectStatLog.getOrDefault("remote_addr", ""));
        jsonObjectResult.put("request", request);
        jsonObjectResult.put("user_agent", jsonObjectStatLog.getOrDefault("http_user_agent", ""));
        jsonObjectResult.put("time_local", DateUtil.dateFormatUTC(jsonObjectStatLog.getString("time_local")));
        jsonObjectResult.put("remote_addr", jsonObjectStatLog.getOrDefault("x_forwarded_for", ""));
        jsonObjectResult.put("uri", jsonObjectStatLog.getOrDefault("uri", ""));
        jsonObjectResult.put("learn_time", "0");
        jsonObjectResult.put("playback_rate", "1");
        jsonObjectResult.put("lts", DateUtil.dateNow());
        if (request == null) {
            return jsonObjectResult;
        }
        String[] s = request.split(" ");
        if (s.length == 1) {
            return jsonObjectResult;
        }
        JSONObject jsonRequest = URLRequest(s[1]);
        jsonObjectResult.putAll(jsonRequest);
        return jsonObjectResult;
    }
}
